<?php
namespace app\api\controller;
use think\File;
use think\facade\Env;
use app\common\model\user\User as UserModel;


class Baseuser extends Base
{
    protected $user_id;
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();

        $this->user_id = Pub::userid();
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login(){
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'hawa' || !$type == 'buss' || !$type == 'acco'|| !$type == 'rebate') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }

        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif,jpeg']);
                $info      = $info->rule("date")->move($save_path);
                if($info==false){return json_encode(['status' => 'error', 'data' => '图片超大或格式不匹配。']);}
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }
}
